package com.kaishengit.web;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.kaishengit.pojo.Document;
import com.kaishengit.pojo.Project;
import com.kaishengit.service.DocumentService;
import com.kaishengit.service.MessageService;
import com.kaishengit.service.ProjectService;
import com.kaishengit.util.DateUtil;

@Results({@Result(name=BaseAction.RELOAD,location="document!list.action",type="redirectAction",params={"id","${document.id}"})})
public class DocumentAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	
	@Resource
	private DocumentService documentService;
	@Resource
	private ProjectService projectService;
	@Resource
	private MessageService messageService;
	
	private Document document;
	private Integer id;
	private Integer projectid;
	private Project project;
	private String filepath;
	
	

	@Override
	public String delete() throws Exception {
		return null;
	}

	@Override
	public String input() throws Exception {
		project = projectService.findById(projectid);
		return INPUT;
	}

	@Override
	public String list() throws Exception {
		System.out.println(id);
		document = documentService.findById(id);
		setSessionAttribute("document", document);
		return MAIN;
	}

	@Override
	public String save() throws Exception {
		document.setCreatetime(DateUtil.getNow());
		document.setProject(projectService.findById(projectid));
		documentService.save(document);
		messageService.saveCreateDocument(document, getCurrentUser());
		return RELOAD;
	}
	
	public String createpdf() throws Exception{
		Document doc = (Document)getSessionAttribute("document"); 
		
		ByteArrayOutputStream bout = documentService.createPDF(doc);
		
		response.setContentType(BaseAction.PDF_TYPE);
		response.setContentLength(bout.size());
		response.setHeader("Content-Disposition", "attachment;filename=" + new String(doc.getTitle().getBytes("gb2312"),"ISO8859-1") + ".pdf");
		OutputStream out = response.getOutputStream();
		bout.writeTo(out);
		return null;
	}

	
	//get and set
	public void setDocument(Document document) {
		this.document = document;
	}

	public Document getDocument() {
		return document;
	}

	public void setProjectid(Integer projectid) {
		this.projectid = projectid;
	}

	public Integer getProjectid() {
		return projectid;
	}

	public void setProject(Project project) {
		this.project = project;
	}

	public Project getProject() {
		return project;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getFilepath() {
		return filepath;
	}

	public void setFilepath(String filepath) {
		this.filepath = filepath;
	}
	
	

}
